<template>
	<view class="local-document-reader">
		<yingbing-whole-reader
		ref="reader"
		:page-type="pageType"
		:font-size="fontSize"
		:line-gap="lineHeight"
		:color="color"
		back-show
		:background="bgColor"
		@single-click="controlsShow = true"
		@long-click="handleEdit"
		@back="handleBack"
		@setCatalog="setCatalog"
		@change="handleChange"></yingbing-whole-reader>
		<view class="position-absolute-cover y-flex" v-show="controlsShow">
			<view class="local-ducment-nav-bar-box" :style="{'background-color': bgColor}">
				<com-nav-bar :title="name" :color="color" status-color="rgba(0,0,0,0)" bg-color="rgba(0,0,0,0)">
					<template #title>
						<com-text lines="2" class="y-flex-1 ml-20 mr-10" weight="bold" line-height="40" size="35" :color="color" :value="name"></com-text>
					</template>
					<template #right>
						<com-icon name="more_android" :color="color" size="40" @click="toolbarShow = true" />
					</template>
				</com-nav-bar>
			</view>
			<view class="y-flex y-flex-1 position-relative y-align-end y-justify-end">
				<view class="position-absolute-cover" @tap="controlsShow = false"></view>
				<view class="y-flex mb-50 mr-30 position-relative" style="z-index: 1;">
					<view class="local-document-btn-circle" :style="{'background': bgColor}" @tap="handleEdit">
						<com-icon name="write" size="38" :color="color"></com-icon>
					</view>
					<view class="local-document-btn-circle mt-40" :style="{'background': bgColor}" @tap="handleMarkInsert">
						<com-icon name="edit" size="38" :color="color"></com-icon>
					</view>
					<view class="local-document-btn-circle mt-40" :style="{'background': bgColor}">
						<text class="fs-24" :style="{color: color}">{{progress + '%'}}</text>
					</view>
				</view>
			</view>
			<view class="local-ducment-tabbar-box" :style="{'background-color': bgColor}">
				<view class="y-flex y-row y-align-center page-padding-gap">
					<text class="fs-26" :style="{color: color}" @tap="handlePrev">后退</text>
					<slider class="y-flex-1" :disabled="!content" block-size="12" :value="progress" @change="handleSliderChange" min="0" max="100" :block-color="color" :activeColor="color" :backgroundColor="app.$utils.hexToRgba(color, 0.5)" />
					<text class="fs-26" :style="{color: color}" @tap="handleNext">前进</text>
				</view>
				<view class="y-flex y-row y-align-center y-justify-between page-padding-gap pt-30 pb-20">
					<view class="y-flex y-align-center" @tap="handleCatalog">
						<com-icon name="sort" :color="color" size="40"></com-icon>
						<text class="fs-26 y-flex-1 ml-30 mr-30 mt-10" :style="{color: color}">目录</text>
					</view>
					<view class="y-flex y-align-center" @tap="handleMark">
						<com-icon name="tag" :color="color" size="40"></com-icon>
						<text class="fs-26 y-flex-1 ml-30 mr-30 mt-10" :style="{color: color}">书签</text>
					</view>
					<view class="y-flex y-align-center" @tap="settingShow = true">
						<com-icon name="settings_light" :color="color" size="40" weight="bold"></com-icon>
						<text class="fs-26 y-flex-1 ml-30 mr-30 mt-10" :style="{color: color}">设置</text>
					</view>
					<view class="y-flex y-align-center" @tap="$store.dispatch('setting/switchSkinMode')">
						<com-icon :name="skinMode == 'night' ? 'creative_fill' : 'creative'" :color="color" size="40"></com-icon>
						<text class="fs-26 y-flex-1 ml-30 mr-30 mt-10" :style="{color: color}">{{skinMode == 'night' ? '日间' : '夜间'}}</text>
					</view>
				</view>
				<com-safe-bottom></com-safe-bottom>
			</view>
		</view>
		<com-popup :visible.sync="settingShow" direction="bottom">
			<view class="y-flex page-padding-gap pt-50 pb-50" :style="{'background': bgColor}">
				<view class="y-flex y-row pb-60">
					<text class="fs-30 mr-30" :style="{color: color}">字号：</text>
					<view class="y-flex y-row y-align-center">
						<view class="local-document-setting-btn" :style="{'border-color': color}" @tap="handleSetFontSize(-1)">
							<com-icon name="move" :color="color" size="30"></com-icon>
						</view>
						<text class="fs-30 ml-20 mr-20" :style="{color: color}">{{fontSize}}</text>
						<view class="local-document-setting-btn" :style="{'border-color': color}" @tap="handleSetFontSize(1)">
							<com-icon name="add" :color="color" size="30"></com-icon>
						</view>
					</view>
				</view>
				<view class="y-flex y-row pb-60">
					<text class="fs-30 mr-30" :style="{color: color}">行高：</text>
					<view class="y-flex y-row y-align-center y-wrap">
						<view class="local-document-setting-btn mr-5"
						:style="{'border-color': color, 'background': line.value == lineHeight ? color : ''}"
						v-for="(line, i) in lines" :key="i"
						@tap="$store.commit('setting/SET_DOCUMENT_LINE_HEIGHT', line.value)">
							<text class="fs-24" :style="{color: line.value == lineHeight ? bgColor : color}">{{line.label}}</text>
						</view>
					</view>
				</view>
				<view class="y-flex y-row pb-60">
					<text class="fs-30 mr-30" :style="{color: color}">翻页：</text>
					<view class="y-flex y-row y-align-center y-wrap">
						<view class="local-document-setting-btn mr-5"
						:style="{'border-color': color, 'background': type.value == pageType ? color : ''}"
						v-for="(type, i) in pageTypes" :key="i"
						@tap="$store.commit('setting/SET_DOCUMENT_PAGE_TYPE', type.value)">
							<text class="fs-24" :style="{color: type.value == pageType ? bgColor : color}">{{type.label}}</text>
						</view>
					</view>
				</view>
				<view class="y-flex y-row">
					<text class="fs-30 mr-30" :style="{color: color}">背景：</text>
					<view class="y-flex y-row y-align-center y-wrap">
						<view class="local-document-setting-circle mr-5"
						:style="{'border-color': theme.bgColor == bgColor ? color : bgColor, 'background': theme.bgColor}"
						v-for="(theme, i) in themes" :key="i"
						@tap="handleSetTheme(theme)">
						</view>
					</view>
				</view>
			</view>
		</com-popup>
		<com-toolbar radius="5" :top="windowTop + 'px'" width="350" :visible.sync="toolbarShow" :bg-color="bgColor">
			<com-toolbar-item :color="color" text="分享文件" @click="app.$utils.shareFile(path)"></com-toolbar-item>
		</com-toolbar>
		<com-popup :visible.sync="editShow" direction="center">
			<view class="y-flex page-padding-gap pt-20" :style="{'background': bgColor}">
				<text class="fs-38" :style="{color: color}">编辑内容</text>
				<textarea v-model="editContent" class="local-document-textarea mt-20 pt-15 pr-15 pb-15 pl-15 fs-35" fixed :auto-height="false" :style="{'border-color': color}"></textarea>
				<view class="y-flex y-row y-align-center ">
					<text class="local-document-textarea-btn y-flex-1 text-align-center fs-34" :style="{color: color}" @tap="editShow = false">取消</text>
					<com-gap width="1px" :color="color"></com-gap>
					<text class="local-document-textarea-btn y-flex-1 text-align-center fs-34" :style="{color: color}" @tap="editModalShow = true">保存</text>
				</view>
			</view>
		</com-popup>
		<com-modal title="记录提示" :content="'本次阅读到 ' + progress + '%\n\n是否保存此次阅读位置'"
		:visible.sync="modalShow"
		:bg-color="skinColor.color_bg_2"
		:title-color="skinColor.color_1"
		:content-color="skinColor.color_2"
		cancel-text="取消保存"
		confirm-text="保存位置"
		@confirm="updatePositon"
		@cancel="handleCancel"></com-modal>
		<com-modal title="保存提示" :content="'确认保存修改后的内容？\n\n点击确认继续'"
		:visible.sync="editModalShow"
		:bg-color="skinColor.color_bg_2"
		:title-color="skinColor.color_1"
		:content-color="skinColor.color_2"
		cancel-text="取消保存"
		confirm-text="保存修改"
		@confirm="handleEditSave"></com-modal>
	</view>
</template>

<script>
	import appMixin from '@/common/mixin/app.js'
	import { writeDocumentContent } from '@/assets/js/native.js'
	import { openDB, closeDB, update, insert, select } from '@/assets/database'
	import { readAllLines } from '@/uni_modules/ybuts-filereader'
	export default {
		mixins: [appMixin],
		computed: {
			id () {
				return this.app.$Route.query.id
			},
			name () {
				return this.app.$Route.query.name
			},
			path () {
				return this.app.$Route.query.path
			},
			type () {
				return this.app.$Route.query.type
			},
			fontSize () {
				return this.$store.getters['setting/GET_DOCUMENT_FONT_SIZE']
			},
			pageType () {
				return this.$store.getters['setting/GET_DOCUMENT_PAGE_TYPE']
			},
			lineHeight () {
				return this.$store.getters['setting/GET_DOCUMENT_LINE_HEIGHT']
			},
			bgColor () {
				return this.skinMode == 'default' ? (this.$store.getters['setting/GET_DOCUMENT_BG_COLOR'] || this.themes[0].bgColor) : this.themes[1].bgColor
			},
			color () {
				return this.skinMode == 'default' ? (this.$store.getters['setting/GET_DOCUMENT_TEXT_COLOR'] || this.themes[0].color) : this.themes[1].color
			},
			//阅读进度
			progress () {
				return ((this.start / this.content.length) * 100).toFixed(2)
			}
		},
		data () {
			return {
				toolbarShow: false,
				modalShow: false,
				settingShow: false,
				controlsShow: false,
				editShow: false,//展示编辑框
				editModalShow: false,//编辑框保存修改确认框展示
				content: '',//文档内容
				charset: '',//文档编码
				catalog: [],//章节列表
				start: 0,//当前页首字符全文位置
				end: 0,//当前页结尾字符全文位置
				text: '',//当前页内容
				editContent: '',//编辑框内容
				lines: [{
					label: '最小',
					value: 5
				},{
					label: '较小',
					value: 10
				},{
					label: '适中',
					value: 15
				},{
					label: '较大',
					value: 20
				},{
					label: '最大',
					value: 25
				}],
				pageTypes: [{
					label: '覆盖',
					value: 'cover'
				},{
					label: '仿真',
					value: 'real'
				},{
					label: '滚动',
					value: 'scroll'
				},{
					label: '无动画',
					value: 'none'
				}],
				themes: [{
					bgColor: '#BFAD8A',
					color: '#2E2B23'
				},{
					bgColor: '#393E41',
					color: '#95A3A6'
				},{
					bgColor: '#fff',
					color: '#333'
				},{
					bgColor: '#e3edcb',
					color: '#010103'
				},{
					bgColor: '#fecccb',
					color: '#010103'
				}]
			}
		},
		onReady() {
			this.start = this.app.$Route.query.position || 0
			this.initReader()
			this.app.$utils.setFullscreen(true)
		},
		onUnload() {
			this.app.$utils.setFullscreen(false)
		},
		methods: {
			initReader () {
				// const Reader = uni.requireNativePlugin('YingBingNativePlugin-Reader');
				// this.content = Reader.readAllLines(this.path);
				// this.$refs.reader.init({
				// 	content: this.content,
				// 	title: this.name,
				// 	start: this.start
				// })
				readAllLines({
					filePath: this.path,
					success: (res) => {
						this.content = res.content
						this.charset = res.charset
						this.$refs.reader.init({
							content: this.content,
							title: this.name,
							start: this.start
						})
						openDB().then(() => {
							update('local', {size: res.size}, 'id = ' + this.id).then(() => {
								closeDB()
							}).catch(() => {
								closeDB()
							})
						})
					},
					fail: (err) => {
						uni.showToast({
							title: '读取文件失败：' + err.message,
							icon: 'none'
						})
					}
				})
			},
			handleBack () {
				this.modalShow = true
			},
			handleChange (e) {
				this.start = e.start
				this.end = e.end
				this.text = e.content
			},
			handleSliderChange (e) {
				this.$refs.reader.change((this.content.length > 500 ? this.content.length - 500 : this.content.length) * (e.detail.value / 100))
			},
			handlePrev () {
				this.$refs.reader.change(Math.max(this.start - (this.content.length * 0.03), 0))
			},
			handleNext () {
				this.$refs.reader.change(Math.min(this.start + (this.content.length * 0.03), Math.max(this.content.length - 500, 0)))
			},
			handleCatalog () {
				const index = this.catalog.findIndex((catalog, i) => catalog.start == this.start || (this.start > catalog.start && this.start < (this.catalog[i + 1]?.start || this.content.length + 1)))
				this.$Router.push({
					path: '/pages/local/catalog',
					query: {
						id: this.id,
						list: this.catalog,
						title: this.name,
						type: 'catalog',
						index: index,
					},
					animationType: 'slide-in-right',
					complete: () => {
						uni.$once('local_document_catalog', (data) => {
							this.$refs.reader.change(data.item.start)
						})
					}
				})
			},
			handleMark () {
				openDB().then(() => {
					select('local_mark', 'resource_id = ' + this.id).then(data=> {
						closeDB()
						const list = data.list
						const index = list.findIndex((item, i) => item.start == this.start || (this.start > item.start && this.start < (list[i + 1]?.start || this.content.length + 1)))
						this.$Router.push({
							path: '/pages/local/catalog',
							query: {
								id: this.id,
								list: list,
								title: this.name,
								type: 'mark',
								index: index
							},
							animationType: 'slide-in-right',
							complete: () => {
								uni.$once('local_document_catalog', (data) => {
									this.$refs.reader.change(data.item.position)
								})
							}
						})
					}).catch(err => {
						closeDB()
						uni.showToast({
							title: err.message,
							icon: 'none'
						})
					})
				})
			},
			//编辑内容展示
			handleEdit () {
				this.editContent = this.text
				this.editShow = true
			},
			handleEditSave () {
				uni.showLoading({
					title: '保存中'
				})
				const content = this.content.substr(0, this.start) + this.editContent + this.content.substr(parseInt(this.end));
				writeDocumentContent({
					filePath: this.path,
					content: content,
					charset: this.charset,
					success: (res) => {
						uni.hideLoading()
						this.editShow = false
						this.initReader()
					},
					fail: (e) => {
						uni.hideLoading()
						this.editShow = false
						uni.showToast({
							title: e.message,
							icon: 'none'
						})
					}
				})
			},
			handleMarkInsert () {
				openDB().then(() => {
					insert('local_mark', {resource_id: this.id, title: this.text.slice(0, 20).replace(/\n/g, ''), position: this.start}).then(()=> {
						closeDB()
						uni.showToast({
							title: '成功插入书签',
							icon: 'none'
						})
					}).catch(err => {
						closeDB()
						uni.showToast({
							title: err.message,
							icon: 'none'
						})
					})
				})
			},
			updatePositon () {
				openDB().then(() => {
					update('local', {position: this.start, progress: this.progress + '%'}, 'id = ' + this.id).then(()=> {
						closeDB()
						this.app.$Router.back()
					}).catch(err => {
						closeDB()
						uni.showToast({
							title: err.message,
							icon: 'none'
						})
						this.app.$Router.back()
					})
				})
			},
			handleCancel () {
				this.app.$Router.back()
			},
			setCatalog (e) {
				this.catalog = e
			},
			handleSetFontSize (value) {
				const fontSize = this.fontSize + value
				if ( fontSize < 15 ) return
				if ( fontSize > 35 ) return
				this.$store.commit('setting/SET_DOCUMENT_FONT_SIZE', fontSize)
			},
			handleSetTheme (theme) {
				this.$store.commit('setting/SET_DOCUMENT_BG_COLOR', theme.bgColor)
				this.$store.commit('setting/SET_DOCUMENT_TEXT_COLOR', theme.color)
			}
		},
		onBackPress(event) {
			if ( event.from == 'backbutton' ) {
				if ( this.toolbarShow ) {
					this.toolbarShow = false
					return true
				}
				if ( this.editShow ) {
					this.editShow = false
					return true
				}
				if ( this.editModalShow ) {
					this.editModalShow = false
					return true
				}
				if ( this.modalShow ) {
					this.modalShow = false
					return true
				}
				if ( this.settingShow ) {
					this.settingShow = false
					return true
				}
				if ( this.controlsShow ) {
					this.controlsShow = false
					return true
				}
				if ( this.content ) {
					this.modalShow = true
					return true
				}
			}
			return false
		}
	}
</script>

<style>
@keyframes local-document-nav-bar-show {
	from {
		transform: translateY(-100%);
	}
	to {
		transform: translateY(0);
	}
}
@keyframes local-document-tabbar-show {
	from {
		transform: translateY(100%);
	}
	to {
		transform: translateY(0);
	}
}
.local-document-reader {
	height: 100%;
	position: relative;
}
.local-ducment-nav-bar-box {
	box-shadow: 0 0 20px rgba(0,0,0,.2);
	animation: local-document-nav-bar-show .3s both;
}
.local-ducment-tabbar-box{
	box-shadow: -10px 0 20px rgba(0,0,0,.2);
	animation: local-document-tabbar-show .3s both;
}
.local-document-setting-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 100rpx;
	height: 40rpx;
	border-radius: 30rpx;
	border-width: 1px;
	border-style: solid;
}
.local-document-setting-circle {
	width: 80rpx;
	height: 80rpx;
	border-radius: 80rpx;
	border-width: 1px;
	border-style: solid;
}
.local-document-btn-circle {
	width: 100rpx;
	height: 100rpx;
	border-radius: 100rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 0 10px rgba(0,0,0,.2);
}
.local-document-textarea {
	height: 800rpx;
	border-width: 1px;
	border-style: solid;
}
.local-document-textarea-btn {
	height: 100rpx;
	line-height: 100rpx;
}
</style>